#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "interface.h"
#include "debug.h"
#include <pthread.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


#define buflen 1024*10


void* test_recv_fun(void* arg){
	msg_t* msg;
	int i=0;
	int fd;
	int len;
	fd = open("../recv_text", O_CREAT|O_WRONLY);
	assert(fd != -1);

	while(1){
		msg = recv_data(1);
	
		printf("recv msg id[%llu] msg->hr.len[%d]\n", msg->hr.id, msg->hr.len);
		len = write(fd, msg->buf, msg->hr.len);
		assert(len ==  msg->hr.len);
		free_msg(msg);
	}

	return NULL;
}


void send_cb(msg_t* msg){
	assert(msg->buf !=NULL);
	free(msg->buf);
} 


void* server_fun(void* arg){
	msg_t* msg;
	while(1){
		msg = recv_data(1);
		send_msg_ack(msg);
	}
}
void usage(char* argv){
	printf("Usage:%s -i id  \n", argv);
}
 
int main(int argc, char* argv[]){
	
	int d = 10;
	queue_t q;
	pthread_t pid_send;
	pthread_t pid_recv;
	int rc;
	int ch;
	int server_id;

   opterr = 0;
   while((ch = getopt(argc, argv, "i:d")) != -1)
   switch(ch)
   {
      case 'i':
		 server_id = atoi(optarg);
		 printf("server id:%d\n", server_id);
		 break;
      case 'd':
         printf("run in daemon\n");
		 break;
      default:
         usage(argv[0]);
		 exit(0);
   }


   sys_init(1,send_cb);
   
   rc = pthread_create(&pid_recv, NULL, server_fun, NULL);
   assert(rc!=-1);

   pthread_join(pid_recv, NULL);
   sys_exit();


}
